package Service;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ParsingXml {
	
      
        
    ArrayList<Previsione> parsedData; //struttura dati che immagazzinerà i dati letti
    ArrayList<String> citta;

    public ArrayList<String> getCitta() {
        return citta;
    }
        
    public ArrayList<Previsione> getParsedData() {  //metodo di accesso alla struttura dati
            return parsedData;
    }
    public void parseCitta(String xmlUrl){
        citta=new ArrayList<String>();
            Document doc;
            try {
                //URLEncoder.encode(xmlUrl, "UTF-8");
                URL url = new URL(xmlUrl);
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                doc = db.parse(url.openStream());   

                XPathFactory factory = XPathFactory.newInstance();
                XPath xPath=factory.newXPath();
                String pattern = "/information/citta";
                NodeList nodes = (NodeList)xPath.evaluate(pattern, doc, XPathConstants.NODESET);
                int i=0;
                while (i<nodes.getLength())
                {   
                    citta.add(nodes.item(i).getTextContent());
                    System.out.println(citta.get(i)+",");
                    i++;
                }   


            //gestione eccezioni
            } catch (SAXException e) {
                    System.out.println(e.toString());
            } catch (Exception e) {
                    System.out.println(e.toString());

            } 
    }
    

    public static Calendar parseTimestamp(String timestamp)throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
        Date d = sdf.parse(timestamp);
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        return cal;
        }
    public void parseXml(String xmlUrl){
                parsedData=new ArrayList<Previsione>();
                Document doc;
                try {
                    //URLEncoder.encode(xmlUrl, "UTF-8");
                    URL url = new URL(xmlUrl);
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    doc = db.parse(url.openStream());   
                    
                    XPathFactory factory = XPathFactory.newInstance();
                    XPath xPath=factory.newXPath();
                    String pattern = "/information/";
                    NodeList nodes = (NodeList)xPath.evaluate(pattern+"@city", doc, XPathConstants.NODESET);
                    String nomeLocalita = (String) nodes.item(0).getNodeValue();    
                    nodes = (NodeList)xPath.evaluate(pattern+"@id", doc, XPathConstants.NODESET);
                    String idLocalita = (String) nodes.item(0).getNodeValue();  
                        
                    System.out.println("Nome Localita: " + nomeLocalita+"\nid città: "+idLocalita);
                    String dayPattern="/information/day";
                    int i=0;
                    NodeList date =(NodeList)xPath.evaluate(dayPattern+"/@value", doc, XPathConstants.NODESET);
                    while (i<date.getLength())
                    {
                        String dataS=(String) date.item(i).getNodeValue();
                        System.out.println(dataS);
                        Calendar data = parseTimestamp(dataS);
                        parsedData.add(new Previsione(Integer.parseInt(idLocalita),nomeLocalita,data));
                        int offset=i+1;
                        nodes = (NodeList) xPath.evaluate(dayPattern+"["+offset+"]/description/text()", doc, XPathConstants.NODESET);
                        parsedData.get(i).setPrevisione(nodes.item(0).getNodeValue());
                        //parsing tMin
                        nodes = (NodeList) xPath.evaluate(dayPattern+"["+offset+"]/tmin/text()", doc, XPathConstants.NODESET);
                        parsedData.get(i).settMin(nodes.item(0).getNodeValue());
                        // parsing Tmax
                        nodes = (NodeList) xPath.evaluate(dayPattern+"["+offset+"]/tmax/text()", doc, XPathConstants.NODESET);
                        parsedData.get(i).settMax(nodes.item(0).getNodeValue());
                        //parsing percentuale precipitazioni
                        nodes = (NodeList) xPath.evaluate(dayPattern+"["+offset+"]/precipitation/text()", doc, XPathConstants.NODESET);
                        parsedData.get(i).setPercentualePrecipitazioni(nodes.item(0).getNodeValue());
                        // vento
                        nodes = (NodeList) xPath.evaluate(dayPattern+"["+offset+"]/wind/text()", doc, XPathConstants.NODESET);
                        parsedData.get(i).setVentoKmh(nodes.item(0).getNodeValue());
                        // pressione
                        nodes = (NodeList) xPath.evaluate(dayPattern+"["+offset+"]/pressure/text()", doc, XPathConstants.NODESET);
                        parsedData.get(i).setPressione(nodes.item(0).getNodeValue());
                        // quota zero
                        nodes = (NodeList) xPath.evaluate(dayPattern+"["+offset+"]/zeroLevel/text()", doc, XPathConstants.NODESET);
                        parsedData.get(i).setQuotaZero(nodes.item(0).getNodeValue());
                        System.out.println(parsedData.get(i));
                        i++;
                    }   
                    
                                
                //gestione eccezioni
                } catch (SAXException e) {
                        System.out.println(e.toString());
                } catch (Exception e) {
                        System.out.println(e.toString());
               
                } 
                
        
    
            }	
    
	  

          public static void main(String args[]){
        try {
            ParsingXml p=new ParsingXml();
            p.parseCitta("http://localhost:8080/Meteo/AndroidServlet?operation=getCitta");
            
            System.out.println();
        } catch (Exception ex) {
            Logger.getLogger(ParsingXml.class.getName()).log(Level.SEVERE, null, ex);
        }
              
          }
	

}
